package com.flyim.framework.netty;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import javax.validation.constraints.Size;

/**
 * @Package: com.flyim.framework.netty
 * @ClassName: NettyServer.java
 * @Description: Netty服务端启动类
 * @author: zhengxiaolong
 * @date: 2025/2/21 14:07
 */
@Configuration
@Slf4j
public class NettyServer {
    @Value("${netty.port:9326}") // 默认端口 9326
    private int port;

    @PostConstruct
    public void start() {
        // 使用独立线程启动 Netty，避免阻塞 Spring Boot 主线程
        new Thread(() -> {
            EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 接收连接线程池
            EventLoopGroup workerGroup = new NioEventLoopGroup(); // 处理连接线程池
            try {
                ServerBootstrap b = new ServerBootstrap();
                b.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new WebSocketInitializer()); // 初始化协议处理器

                Channel channel = b.bind(port).sync().channel();
                log.info("Netty服务端已启动，监听端口{}", port);
                // 阻塞等待关闭
                channel.closeFuture().sync();
            } catch (InterruptedException e) {
                log.error("Netty服务端启动失败，监听端口{}", port);
                e.printStackTrace();
            } finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }).start();
    }
}